/*
 * Copyright 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.livepass.android.girlspicks.activities;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.livepass.android.girlspicks.MyApplication;
import com.livepass.android.girlspicks.R;
import com.livepass.android.girlspicks.adapters.ArticleAdapter;
import com.livepass.android.girlspicks.adapters.ArticleTableAdapter;
import com.livepass.android.girlspicks.adapters.PushMeassageAdapter;
import com.livepass.android.girlspicks.models.Article;
import com.livepass.android.girlspicks.utils.JSONParser;
import com.livepass.android.girlspicks.utils.Utilities;
import com.livepasspush.sdk.LivepassPushSDK;

/**
 * Simple Fragment used to display some meaningful content for each page in the
 * sample's {@link android.support.v4.view.ViewPager}.
 */
public class ContentFragment extends Fragment {

	private static final String KEY_TITLE = "title";
	private static final String KEY_INDICATOR_COLOR = "indicator_color";
	private static final String KEY_DIVIDER_COLOR = "divider_color";
	private static final String KEY_TEXT_COLOR = "text_color";
	private Activity mActivity;

	private PullToRefreshListView mPullRefreshListView;
	List<Article> listArticles;
	ArticleAdapter articleAdapter;
	private int currentPage = 1;
	private boolean isLoadMore = true;
	public static Article article;
	// public static Article article;

	ListView lvSetting;
	LinearLayout llNoBookmark;
	TextView tvIntrodue;
	private LinearLayout llLoading;
	private AsyncGetArticleList loader;
	private AsyncSetArticleView loaderView;
	private ArticleTableAdapter articleTableAdapter;

	/**
	 * @return a new instance of {@link ContentFragment}, adding the parameters
	 *         into a bundle and setting them as arguments.
	 */
	public static ContentFragment newInstance(CharSequence title,
			int indicatorColor, int dividerColor, int textColor) {
		Bundle bundle = new Bundle();
		bundle.putCharSequence(KEY_TITLE, title);
		bundle.putInt(KEY_INDICATOR_COLOR, indicatorColor);
		bundle.putInt(KEY_DIVIDER_COLOR, dividerColor);
		bundle.putInt(KEY_TEXT_COLOR, textColor);

		ContentFragment fragment = new ContentFragment();
		fragment.setArguments(bundle);

		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = activity;
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Push SDK
		sPushMessageList = new ArrayList<HashMap<String, String>>();
		sAdapter = new PushMeassageAdapter(getActivity(), sPushMessageList);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.pager_item, container, false);
	}

	@Override
	public void onResume() {
		if (mActivity != null)
			articleAdapter.notifyDataSetChanged();
		super.onResume();
		LivepassPushSDK.isActive = true;
		// lvSetting.setAdapter(sAdapter);
	}

	@Override
	public void onPause() {
		super.onPause();
		LivepassPushSDK.isActive = false;
	}
	
	public void reloadCommentCountInListview(String cmtCount) {
		if(article != null)
			article.setCmtCount(cmtCount);
		if(articleAdapter != null)
			articleAdapter.notifyDataSetChanged();
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		llLoading = (LinearLayout) view.findViewById(R.id.llLoading);
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.list_article);
		tvIntrodue = (TextView) view
				.findViewById(R.id.tvIntrodue);
		lvSetting = (ListView) view.findViewById(R.id.list_setup);

		llNoBookmark = (LinearLayout) view.findViewById(R.id.llNoBookmark);

		articleTableAdapter = ArticleTableAdapter.getInstance(getActivity());

		loadPageItem(MyApplication.AP);
	}
	
	private void loadPageItem(final String ap) {
		Bundle args = getArguments();

		if (args != null) {
			
			// set data to each tabs
			if (!(args.getString(KEY_TITLE)).equals(getString(
					R.string.tab_terms_of_use).toString())) {
				if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_toppic).toString())) {
					loadArticle("1", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_popularity).toString())) {
					loadArticle("2", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_gossip).toString())) {
					loadArticle("3", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_political_economic).toString())) {
					loadArticle("4", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_love).toString())) {
					loadArticle("5", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_adults).toString())) {
					loadArticle("6", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_column).toString())) {
					loadArticle("7", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_summary).toString())) {
					loadArticle("8", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_beauty).toString())) {
					loadArticle("9", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_fashion).toString())) {
					loadArticle("10", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_gourmet).toString())) {
					loadArticle("11", ap);
				} else if (args.getString(KEY_TITLE).equals(
						getText(R.string.tab_bookmark).toString())) {
					listArticles = articleTableAdapter.getAllArticle();
					if (listArticles.size() > 0) {
						articleAdapter = new ArticleAdapter(getActivity(),
								R.layout.article_list_item, listArticles);
					} else {
						llNoBookmark.setVisibility(View.VISIBLE);
						mPullRefreshListView.setVisibility(View.GONE);
						// lvSetting.setVisibility(View.GONE);
					}
				}
				ListView actualListView = mPullRefreshListView
						.getRefreshableView();

				// Need to use the Actual ListView when registering for Context Menu
				registerForContextMenu(actualListView);

				actualListView
						.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								Intent intentArticle = new Intent(
										getActivity(), ArticleActivity.class);
								Bundle bundle = new Bundle();
								article = articleAdapter.getItem(position - 1);
								bundle.putSerializable("article", article);
								intentArticle.putExtras(bundle);
								//getActivity().startActivity(intentArticle);
								getActivity().startActivityForResult(intentArticle, MyApplication.COMMENT);
								getActivity().overridePendingTransition(
										R.anim.slide_in_right,
										R.anim.slide_out_left);
								loaderView = new AsyncSetArticleView();
								loaderView.execute(article.getArticleId());
							}

						});

				actualListView.setAdapter(articleAdapter);
			} else if ((args.getString(KEY_TITLE).equals(getText(
					R.string.tab_terms_of_use).toString()))) {
				ArrayList<String> listSettings = new ArrayList<String>();
				listSettings.add("利用規約");
				listSettings.add("プライバシーポリシー");
				listSettings.add("お問い合わせ・削除依頼‏");

				tvIntrodue.setVisibility(View.VISIBLE);

				ArrayAdapter<String> adapter = new ArrayAdapter<String>(
						getActivity(), R.layout.settings_list_item,
						R.id.tvTitle, listSettings) {
					@Override
					public View getView(final int position, View convertView,
							ViewGroup parent) {
						View view = super
								.getView(position, convertView, parent);
						view.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								switch (position) {
								case 0:
									Intent intentNotice = new Intent(
											getContext(),
											WebviewNoticeActivity.class);
									startActivity(intentNotice);
									break;
								case 1:
									Intent intentPolicy = new Intent(
											getContext(),
											WebviewPolicyActivity.class);
									startActivity(intentPolicy);
									break;
								case 2:
									try {
										Intent emailIntent = new Intent(
												android.content.Intent.ACTION_SEND);
										String[] recipients = new String[] { "support@bravo-global.co" };
										// String[] ccList =
										// {"thaivu101@gmail.com"};
										emailIntent
												.putExtra(
														android.content.Intent.EXTRA_EMAIL,
														recipients);
										// emailIntent.putExtra(android.content.Intent.EXTRA_CC,
										// ccList);
										emailIntent
												.putExtra(
														android.content.Intent.EXTRA_SUBJECT,
														"お問い合ゎせ・削除依頼");
										emailIntent
												.putExtra(
														android.content.Intent.EXTRA_TEXT,
														"");
										emailIntent.setType("text/plain");
										startActivity(Intent.createChooser(
												emailIntent, "send mail..."));
									} catch (Exception e) {
										Toast.makeText(getContext(),
												"" + e.getMessage(),
												Toast.LENGTH_SHORT).show();
									}
									break;
								default:
									break;
								}

							}
						});
						return view;
					}
				};
				lvSetting.setAdapter(adapter);
				mPullRefreshListView.setVisibility(View.GONE);
				llNoBookmark.setVisibility(View.GONE);
				lvSetting.setVisibility(View.VISIBLE);
			}
		}
	}
	
	/**
	 * Load list article
	 * @param categoryId
	 * @param ap
	 */
	private void loadArticle(final String categoryId, final String ap) {
		if (loader == null) {
			listArticles = new ArrayList<Article>();
			loader = new AsyncGetArticleList();
			loader.execute(categoryId, ap, "1");
			// set adapter for listview
			articleAdapter = new ArticleAdapter(getActivity(),
					R.layout.article_list_item, listArticles);
		}
		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {

						String label = SimpleDateFormat.getDateInstance(
								SimpleDateFormat.LONG, Locale.CHINA)
								.format(System.currentTimeMillis());

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel("最終更新：" + label);

						// Do work to refresh the list here.
						new PullToRefreshTask().execute(ap);
					}
				});
		// Add an end-of-list listener
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						if (isLoadMore) {
							loader = new AsyncGetArticleList();
							++currentPage;
							loader.execute(categoryId, ap, "" + currentPage);
							Log.d("PAGE", "" + currentPage);
						}
					}
				});
	}

	public void reloadBookmark() {
		if (getActivity() != null) {
			if (articleTableAdapter == null) {
				articleTableAdapter = ArticleTableAdapter
						.getInstance(getActivity());
			}
			listArticles = articleTableAdapter.getAllArticle();
			if (listArticles.size() > 0) {
				if (articleAdapter != null)
					articleAdapter.clear();
				articleAdapter = new ArticleAdapter(getActivity(),
						R.layout.article_list_item, listArticles);
				if (mPullRefreshListView != null) {
					mPullRefreshListView.setAdapter(articleAdapter);
				}
			} else {
				llNoBookmark.setVisibility(View.VISIBLE);
				mPullRefreshListView.setVisibility(View.GONE);
			}
		}
	}

	private class PullToRefreshTask extends
			AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			// Simulates a background job.
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			return params[0];
		}

		@Override
		protected void onPostExecute(String result) {
			loadAP(result);
			mPullRefreshListView.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	/**
	 * 
	 * @author Vaio
	 * @param category
	 * @param ap
	 * @param page
	 */
	private class AsyncGetArticleList extends
			AsyncTask<String, JSONObject, ArrayList<Article>> {

		@Override
		protected ArrayList<Article> doInBackground(String... params) {

			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("category_id", params[0]);
			param.put("ap", params[1]);
			param.put("page", params[2]);

			JSONObject jsonObject = null;
			ArrayList<Article> listArticles = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/get_article_by_category",
						param);
				// Parse the JSON Object
				JSONParser parser = new JSONParser();
				listArticles = parser.parserArticle(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				// Toast.makeText(con,
				// "Can't connect to the network. Please try again!",
				// Toast.LENGTH_SHORT).show();
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return listArticles;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			llLoading.setVisibility(View.VISIBLE);
		}

		@Override
		protected void onPostExecute(ArrayList<Article> result) {

			if (result != null && result.size() != 0) {
				for (int i = 0; i < result.size(); i++) {
					listArticles.add(result.get(i));
				}
				//set load more
				if(result.size()<20) {
					isLoadMore = false;
				}
				articleAdapter.notifyDataSetChanged();
			}
			llLoading.setVisibility(View.GONE);
		}

	}

	private class AsyncSetArticleView extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			String re = null;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);
			param.put("client_id", MyApplication.USER_ID);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_article_view", param);
				re = jsonObject.getString("status");
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
				return re;
			} catch (IOException e1) {
				e1.printStackTrace();
				return re;
			} catch (JSONException e) {
				e.printStackTrace();
				return re;
			}
			return re;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {

			if (result != null) {
				// success
				// nothing
			} else {
				// fail
				// nothing
			}
		}
	}

	public void loadAP(String ap) {
		if (mActivity != null){
			if(articleAdapter != null){
				articleAdapter.clear();
			}
			loader = null;
			loadPageItem(ap);
		}
	}

	// ////////////////////////////////
	static PushMeassageAdapter sAdapter;
	static private ArrayList<HashMap<String, String>> sPushMessageList;

	public static ArrayList<HashMap<String, String>> getPushMessageList() {
		if (sPushMessageList == null) {
			clearPushMessageList();
		}
		return sPushMessageList;
	}

	public static void addList(String message) {
		HashMap<String, String> map = new HashMap<String, String>();
		try {
			JSONObject json = new JSONObject(message);
			map.put("mid", json.getString("mid"));
			map.put("alert", json.getString("alert"));
			map.put("json", message);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		getPushMessageList().add(map);
		if (sAdapter != null) {
			sAdapter.notifyDataSetChanged();
		}
	}

	private static void clearPushMessageList() {
		sPushMessageList = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("mid", "dummy_id");
		map.put("alert", "dummy_alert");
		map.put("json", "dummy_data");
		sPushMessageList.add(map);
		if (sAdapter == null) {
			sAdapter.notifyDataSetChanged();
		}
	}
}